package com.ruoyi.common.jedis;

import com.ruoyi.common.config.Global;
import org.springframework.cache.annotation.CachingConfigurerSupport;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;
import redis.clients.jedis.JedisPoolConfig;

public class JedisConfig extends CachingConfigurerSupport {
    private static String host = Global.getConfig("spring.redis.host");
    private static int port = Global.getInt("spring.redis.port", 6379);
    private static int timeout = Global.getInt("spring.redis.timeout", 6000);
    private static int maxActive = Global.getInt("spring.redis.jedis.pool.max-active", 2000);
    private static int maxIdle = Global.getInt("spring.redis.jedis.pool.max-idle", 100);
    private static int minIdle = Global.getInt("spring.redis.jedis.pool.min-idle", 50);
    private static long maxWaitMillis = Global.getInt("spring.redis.jedis.pool.max-wait", -1);

    private static JedisPool jedisPool;

    static {
        JedisPoolConfig config = new JedisPoolConfig();
        config.setMaxTotal(maxActive);
        config.setMaxIdle(maxIdle);
        config.setMinIdle(minIdle);//设置最小空闲数
        config.setMaxWaitMillis(maxWaitMillis);
        config.setTestOnBorrow(true);
        config.setTestOnReturn(true);
        //Idle时进行连接扫描
        config.setTestWhileIdle(true);
        //表示idle object evitor两次扫描之间要sleep的毫秒数
        config.setTimeBetweenEvictionRunsMillis(30000);
        //表示idle object evitor每次扫描的最多的对象数
        config.setNumTestsPerEvictionRun(10);
        //表示一个对象至少停留在idle状态的最短时间，然后才能被idle object evitor扫描并驱逐；这一项只有在timeBetweenEvictionRunsMillis大于0时才有意义
        config.setMinEvictableIdleTimeMillis(60000);
        jedisPool = new JedisPool(config, host, port, timeout);
    }

    /**
     * 获取一个jedis对象
     * @return jedis连接对象
     */
    public static Jedis getJedis() {
        return jedisPool.getResource();
    }

    /**
     * 关闭jedis连接
     * @param jedis jedis连接对象
     */
    public static void closeJedis(Jedis jedis) {
        if (jedis != null) {
            jedis.close();
        }
    }
}
